import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;

import java.io.File;

public class Pdf2Split {

    // 输出文件夹路径
    private final static String outputFolder = "C:/Users/hongz/Desktop/pdf";
    // 输入文件路径
    private final static String inputFilePath = "C:/Users/hongz/Desktop/pdf/二标段 （车票名单）.pdf";
    // 文件名称
    private final static File file = new File(inputFilePath);

    public static void main(String[] args) {
        split2One();
        start2End(2, 5);
    }

    /**
     * 分割成每一页
     */
    public static void split2One() {
        try {
            PDDocument document = PDDocument.load(file);
            int pageCount = document.getNumberOfPages();
            if (pageCount == 0) {
                throw new RuntimeException("转换失败,取出页数为0");
            }
            for (int i = 0; i < pageCount; i++) {
                PDPage page = document.getPage(i);
                PDDocument output = new PDDocument();
                output.addPage(page);

                String outputPath = outputFolder + File.separator + file.getName().replace(".pdf", "") + (i + 1) + ".pdf";
                output.save(outputPath);
                output.close();
            }
            System.err.println("转换完成");
        } catch (Exception e) {
            System.err.println("转换出现异常，" + e.getMessage());
        }
    }

    /**
     * 分割固定的页数
     *
     * @param start 开始页
     * @param end   结束页
     */
    public static void start2End(int start, int end) {
        try {
            PDDocument document = PDDocument.load(file);
            int pageCount = document.getNumberOfPages();
            if (pageCount == 0) {
                throw new RuntimeException("转换失败,取出页数为0");
            }
            PDDocument output = new PDDocument();
            for (int i = start - 1; i < end; i++) {
                PDPage page = document.getPage(i);
                output.addPage(page);
            }
            String outputPath = outputFolder + File.separator + file.getName().replace(".pdf", "") + "_" + start + '-' + end + ".pdf";
            output.save(outputPath);
            output.close();
            System.err.println("转换完成");
        } catch (Exception e) {
            System.err.println("转换出现异常，" + e.getMessage());
        }
    }

}
